import { useRef, useState } from 'react';
import { lineString, featureCollection } from '@turf/helpers';
// import source from './data/source.json';
import AMap from './amap';
import './App.css';

// window.testData = source;

const transformLineCollection = data => {
  if (data && Array.isArray(data)) {
    return featureCollection(data.map((item, index, arr) => {
      return lineString([item.coordinates, arr[index < arr.length - 1 ? index + 1 : index].coordinates], item.properties);
    }));
  }
  return featureCollection([]);
}

function App() {
  const ref = useRef(null);
  const [indicators, setIndicators] = useState(null);
  const [colors, setColors] = useState(window.myMap.colors);

  const onLoad = () => {
    // const amap = ref.current.getAmap();
    const amapUI = ref.current.getAmapUI();
    const aloca = ref.current.getAloca();
    const loca = ref.current.getLoca();
    const map = ref.current.getMap();

    window.myMap.setMapCenter = center => {
      if (center) map.setCenter(center.coordinates);
    }

    const renderOptions = {
      //点的样式
      pointStyle: {
        fillStyle: 'red',
        width: 5,
        height: 5
      },
      getGroupId: function (item, idx) {
        return window.myMap.colors.findIndex(color => !color.value || item.properties.value < color.value);
      },
      groupStyleOptions: function (gid) {
        return {
          pointStyle: {
            fillStyle: `rgb(${window.myMap.colors[gid].color.toString()}`
          }
        };
      }
    };
    const linkLayer = new aloca.LineLayer({
      zIndex: 20,
      opacity: 1,
      visible: true,
      zooms: [2, 22],
    });

    const renderLinkLayer = data => {
      if (!data || !Array.isArray(data) || data.length === 0) return;
      const geo = new aloca.GeoJSONSource({
        data: transformLineCollection(data),
      });
      linkLayer.setSource(geo);
      linkLayer.setStyle({
        color: function (index, item) {
          const color = window.myMap.colors.find(color => !color.value || item.properties.value < color.value);
          return `rgba(${color ? color.color.toString() : [0, 0, 0].toString()}, 0.6)`;
        },
        lineWidth: 2,
      });
      loca.add(linkLayer);
    }

    const clearLinkLayer = () => {
      loca.remove(linkLayer);
    }

    const pointSimplifierIns = new amapUI.PointSimplifier({
      zIndex: 115,
      autoSetFitView: false,
      map: map,
      getPosition: function (item) {
        if (!item) {
          return null;
        }
        return item.coordinates;
      },
      getHoverTitle: function (dataItem, idx) {
        setIndicators(dataItem.properties.indicators);
        return dataItem.properties.value;
      },
      //使用GroupStyleRender
      renderConstructor: amapUI.PointSimplifier.Render.Canvas.GroupStyleRender,
      renderOptions,
    });

    window.myMap.setMapColors = () => {
      setColors(window.myMap.colors);
      pointSimplifierIns.renderLater([10]);
    }

    window.myMap.setMapData = data => {
      pointSimplifierIns.setData(data);
      renderLinkLayer(data);
    }

    window.myMap.clearMapData = () => {
      pointSimplifierIns.setData([]);
      clearLinkLayer();
    }
  }

  return (
    <div className="App">
      <AMap ref={ref} onLoad={onLoad} />
      <div className="modal">
        <table>
          <thead>
            <tr>
              <th style={{ width: 40 }}>序号</th>
              <th style={{ width: 60 }}>名称</th>
              <th style={{ width: 120 }}>浓度（ug/m³）</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(indicators) && indicators.map((item, index) => (
              <tr key={index}>
                <td>{index + 1}</td>
                <td>{item.title}</td>
                <td>{item.value}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="panel">
        {Array.isArray(colors) && colors.map(item => (
          <div key={item.value || 'max'} className="item">
            <div className="color" style={{ backgroundColor: `rgb(${item.color.toString()})` }} />
            <div className="value">&lt; {item.value || 'Max'}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
